<?php

class SelisteController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/selavenir';
	public $skin = "";
	
	public function init()
	{
		$session=new CHttpSession;
		$session->open();
		if (isset($session["skin"])) $this->skin = $session["skin"];
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', 
				'actions'=>array('create','update','admin','update_pass','update_grains','tab_grains'),
				'expression' => array($this, 'isAdmin'),
			),
			array('allow', 
					'actions'=>array('liste','view','mailbox','mail','delmail','newmail','sentmail','smail','rmail','compte','update_compte','update_compte_pass','update_compte_grains','getSelistesGrain'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	/**
	*  Function to control access
	* @param CWebUser current user obj
	* @param CAccessRule access rule obj
	*/
	public function isAdmin($user, $rule)
	{ 
		if(isset($user->admin) && $user->admin)
			return true;
		else
			return false;
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	/* boite de réception */
	public function actionMailbox()
	{
		$model=new Message('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Message']))
			$model->attributes=$_GET['Message'];
		$model->destinataire->idseliste = Yii::app()->user->id;
		$model->destinataire->del_rec = NULL;
		$this->render('mailbox',array(
				'model'=>$model,
		));
	}
	
	/* détail d'un message */
	public function actionMail($id)
	{
		$model=Message::model()->findByattributes(array("id"=>$id),array('with'=>'destinataires','condition'=>"idseliste=".Yii::app()->user->id));
		if ($model) {
			if ($model->destinataires[0]->lu == NULL) {
				$destinataire = Destinataire::model()->findByPk(array("idseliste"=>Yii::app()->user->id,"idmessage"=>$model->id));
				$destinataire->lu = date('Y-m-d H:i:s');
				$destinataire->save();
			}
			$this->render('mail',array(
					'model'=>$model,
			));
		} else {
			throw new CHttpException(404,'Ce message n\'existe pas.');
		}
	}
	
	/* détail d'un message envoyé */
	public function actionSmail($id)
	{
		$model=Message::model()->findByAttributes(array("id"=>$id,"idseliste_em"=>Yii::app()->user->id));
		if ($model) {
			$this->render('smail',array(
					'model'=>$model,
			));
		} else {
			throw new CHttpException(404,'Ce message n\'existe pas.');
		}
	}

	/* suppression de message */
	public function actionDelmail($id)
	{
		$model=Message::model()->findByattributes(array("id"=>$id,"idseliste_em"=>Yii::app()->user->id));
		if (!$model) $model=Message::model()->findByattributes(array("id"=>$id,"idseliste_rec"=>Yii::app()->user->id));
		if ($model) {
			if ($model->idseliste_em == Yii::app()->user->id) {
				if ($model->del_rec == 1 || $model->lu == NULL) {
					$model->delete();
				} else {
					$model->del_em = 1;
					$model->save();
				}
			} elseif ($model->idseliste_rec == Yii::app()->user->id) {
				if ($model->del_em == 1 || $model->auto == 1) {
					$model->delete();
				} else {
					$model->del_rec = 1;
					$model->save();
				}
			} 
		} else {
			throw new CHttpException(404,'Ce message n\'existe pas.');
		}
		
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	
	}
	
	/* nouveau message */
	public function actionNewmail()
	{
		$model=new Message('insert');
		$dest = new Destinataire();
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['Message']))
		{
			$model->attributes=$_POST['Message'];
			$model->date = date('Y-m-d H:i:s');
			$model->idseliste_em = Yii::app()->user->id;
			if (!isset($_POST['destinataires'])) {
				$dest->addError('idseliste', 'Merci de choisir au moins un destinataire.');
			}
			if ($model->validate()) {
				if($model->save()) {
					// le message est sauvegardé, on ajoute les destinataires
					foreach ($_POST['destinataires'] as $id) {
						$seliste = Seliste::model()->findByPk($id);
						$liste[] = array("id"=>$seliste->id,"email"=>$seliste->email,"modecontact"=>$seliste->modecontact,"notif_message"=>$seliste->notif_message,"notif_demande"=>$seliste->notif_demande);
					}
					// envoi du message de demande au(x) séliste(s) concerné(s)
					Message::send_message('message',$model->id,$model->idseliste_em,$liste);
					$this->redirect(array('seliste/mailbox'));
				}
			}
		}
		
		$this->render('newmail',array(
				'model'=>$model,
				'dest'=>$dest
		));
	}
	
	/* répondre à un message */
	public function actionRmail($id)
	{
		$verif=Message::model()->findByattributes(array("id"=>$id,"idseliste_rec"=>Yii::app()->user->id));
		if (!$verif) {
			throw new CHttpException(404,'Ce message n\'existe pas.');
		} else {
		
			$model=new Message('insert');
			$model->sujet = "Re: " . $verif->sujet;
			$model->idseliste_rec = $verif->idseliste_em;
			$model->idmessage = $id;
		
			// Uncomment the following line if AJAX validation is needed
			// $this->performAjaxValidation($model);
		
			if(isset($_POST['Message']))
			{
				$model->attributes=$_POST['Message'];
				$model->date = date('Y-m-d H:i:s');
				$model->idseliste_em = Yii::app()->user->id;
				if($model->save()) {
					$this->redirect(array('seliste/mailbox'));
				}
			}
		
			$this->render('newmail',array(
					'model'=>$model,
			));
		}
	}
	
	/* messages envoyés */
	public function actionSentmail()
	{
		$model=new Message('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Message']))
			$model->attributes=$_GET['Message'];
		$model->idseliste_em = Yii::app()->user->id;
		$model->del_em = 0;
		$model->auto = 0;
		$this->render('sentmail',array(
				'model'=>$model,
		));
	}
	
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($compte=false)
	{
		$model=new Seliste('insert');
		
		if (!$compte) $this->layout = "selavenir_admin";

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Seliste']))
		{
			$model->attributes=$_POST['Seliste'];
			$model->date_inscr = substr($_POST['Seliste']['date_inscr'],6,4) . "-" . substr($_POST['Seliste']['date_inscr'],3,2) . "-" . substr($_POST['Seliste']['date_inscr'],0,2);
			$model->pwd = md5($_POST['Seliste']['pwd']);
			if($model->save()) {
				HistoAdmin::historise($this,$model->id,Yii::app()->user->id);
				$this->redirect(array('update_grains','id'=>$model->id));
			}
		}

		$this->render('create',array(
			'model'=>$model,
			'compte'=>$compte
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id,$compte=false)
	{
		$model=$this->loadModel($id);
		
		if (!$compte) $this->layout = "selavenir_admin"; 

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Seliste']))
		{
			$model->attributes=$_POST['Seliste'];
			$model->date_inscr = explode('/',$model->date_inscr);
			$model->date_inscr = $model->date_inscr[2].'-'.$model->date_inscr[1].'-'.$model->date_inscr[0];
			if($model->save()) {
				HistoAdmin::historise($this,$model->id,Yii::app()->user->id);
				if ($compte) {
					$this->redirect(array('compte'));
				} else {
					$this->redirect(array('admin'));
				}
			}
		}
		if ($compte) {
			$this->render('update_compte',array(
					'model'=>$model,
			));
		} else {
			$this->render('update',array(
				'model'=>$model,
			));
		}
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate_compte()
	{
		$this->actionUpdate(Yii::app()->user->id,true);
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate_pass($id,$compte=false)
	{
		$model=$this->loadModel($id);
		$model->scenario = "update_pass";
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Seliste']))
		{
			$model->pwd=md5($_POST['Seliste']['pwd']);
			$model->pwd2=md5($_POST['Seliste']['pwd2']);
			if($model->save()) {
				HistoAdmin::historise($this,$model->id,Yii::app()->user->id);
				if ($compte) {
					$this->redirect(array('compte'));
				} else {
					$this->redirect(array('admin'));
				}
			}
		}

		if ($compte) {
			$this->render('update_compte_pass',array(
					'model'=>$model,
			));
		} else {
			$this->render('update_pass',array(
					'model'=>$model,
			));
		}
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate_compte_pass()
	{
		$this->actionUpdate_pass(Yii::app()->user->id,true);
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate_grains($id,$compte=false)
	{
	
		$model=$this->loadModel($id);
		
		if (!$compte) $this->layout = "selavenir_admin";

		if(isset($_POST['checkgrain']))
		{
			// mise à jour des grains
			// on ajoute les grains non cochés précédemment
			$coches = array();
			foreach ($_POST['checkgrain'] as $key=>$groupe) {
				if (!($propose = Propose::model()->findByPk(array('idseliste'=>$id,'idgrain'=>$key)))) {
					$propose = new Propose();
					$propose->idseliste = $id;
					$propose->idgrain = $key;
					$propose->date_propose = date('Y-m-d H:i:s');
					$propose->save();
				}
				$coches[] = $key;
			}
			// on supprime les grains décochés
			// attention aux grains qui ne sont pas visibles ! 
			// (ex : grains non validés et non  visibles par l'admin qui met à jour la liste des grains du séliste)
			foreach ($model->grains as $grain) {
				if (!in_array($grain->id,$coches)) {
					if ($grain->status == 1 || ($grain->status == 0 && (Yii::app()->user->admin_grain || ($grain->idseliste == Yii::app()->user->id)))) {
						// suppression du grain
						Propose::model()->findByPk(array('idseliste'=>$id,'idgrain'=>$grain->id))->delete();
					}
				}
			}
			HistoAdmin::historise($this,$model->id,Yii::app()->user->id);
			if ($compte) {
				$this->redirect(array('compte'));
			} else {
				$this->redirect(array('admin'));
			}
		}

		if ($compte) {
			$this->render('update_compte_grains',array(
					'model'=>$model,
			));
		} else {
			$this->render('update_grains',array(
					'model'=>$model,
			));
		}
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate_compte_grains()
	{
		$this->actionUpdate_grains(Yii::app()->user->id,true);
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();
		HistoAdmin::historise($this,$id,Yii::app()->user->id);
		
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Seliste');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin($liste=false)
	{
		if (!$liste) $this->layout = "selavenir_admin";
		$model=new Seliste('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Seliste']))
			$model->attributes=$_GET['Seliste'];

		$this->render('admin',array(
			'model'=>$model,
			'liste'=>$liste
		));
	}
	
	/**
	 * Liste des sélistes
	 */
	public function actionListe()
	{
		$this->actionAdmin(true);
	}
	
	public function actionTab_grains($id)
	{
	
		$model=$this->loadModel($id);
		
		$grains_seliste = array();
		foreach ($model->grains as $grain) {
			$grains_seliste[] = $grain->id;
		}

		$html = $this->renderPartial('_tab_grains',array(
			'grains_seliste'=>$grains_seliste,
			'domaine'=>$_POST['domaine'],
			'type'=>$_POST['type']
		),true,true);
		
		echo CJSON::encode(array(
			"html"=>$html,
			"type"=>$_POST['type'],
			"domaine"=>$_POST['domaine']
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Seliste the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Seliste::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Seliste $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='seliste-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * Compte utilisateur
	 */
	public function actionCompte()
	{
		$this->render('view_compte',array(
				'model'=>$this->loadModel(Yii::app()->user->id),
		));
	}
	
	public function actionGetSelistesGrain($id)
	{
		$selistes = Seliste::model()->getSelistesGrain($id);
		$retour = array();
		foreach ($selistes as $seliste) {
			if ($seliste->id <> Yii::app()->user->id) {
				/*$nom = $seliste->id;
				if (($seliste->v_pseudo == 1) || ($seliste->v_nom == 1) || ($seliste->v_prenom == 1) || Yii::app()->user->admin) $nom .= " (";
				if ($seliste->v_pseudo == 1 || Yii::app()->user->admin) $nom .= $seliste->pseudo;
				if (($seliste->v_nom == 1) || ($seliste->v_prenom == 1) || Yii::app()->user->admin) $nom .= " - ";
				if ($seliste->v_nom == 1 || Yii::app()->user->admin) $nom .= $seliste->nom . " ";
				if ($seliste->v_prenom == 1 || Yii::app()->user->admin) $nom .= $seliste->prenom;
				if (($seliste->v_pseudo == 1) || ($seliste->v_nom == 1) || ($seliste->v_prenom == 1) || Yii::app()->user->admin) $nom .= ")";*/
				$nom = $seliste->pseudo;
				$retour[] = array("id"=>$seliste->id,"seliste"=>$nom);
			}
		}
		echo CJSON::encode($retour);
	}

}
